import time

class Task:
    def __init__(self, id, index):
        self.dependencies =[] # dependencies, a list of tasks
        self.id = id
        self.index = index
        self.speech = None # speech at beginning of task
        self.query = None  # speech asking user if task is done
        self.duration = None  # in seconds
        self.time_finished = None
        self.time_started = None
        self.time_last_queried = None
    def elapsed(self):      # return elapsed time since start
        return time.time()-self.time_started
    def start(self, time_started=None):
        self.time_started= time_started or time.time()
    def stop(self, time_finished=None):
        self.time_finished= time_finished or time.time()
    def completed(self):
        return self.time_finished!=None
    def can_start(self):
        if self.started():
            return False
        for d in self.dependencies:
            if not d.completed():
                return False
        return True
    def started(self):
        return self.time_started!=None
    def is_active(self):
        return self.started() and not self.completed()
    def ETA(self):
        if self.time_finished:
            return self.time_finished
        if self.time_started:
            return self.time_started + self.duration
        if self.dependencies:
            estimated_start = max(d.ETA() for d in self.dependencies)
        else:
            estimated_start = time.time()
        return estimated_start + self.duration
    def query_now(self, time_queried = None):
        self.time_last_queried = time_queried or time.time()
    def is_overdue(self, current_time=None):
        if not self.time_started  or self.time_finished:
            return False
        return (self.time_started + self.duration) < (current_time or time.time())
    def __repr__(self):
        return "<<%s: [%s] - started %s, complted %s,  depends on %s >>" % (self.id, 
                                                                      self.speech[:10], 
                                                                      self.time_started, 
                                                                      self.time_finished, [t.id for t in self.dependencies])


    
def find_available_tasks(ta):
    '''search with brute force for all available tasks'''
    return [t for t in ta if t.can_start()]

def find_active_tasks(ta):
    '''search with brute force for all active tasks'''
    return [t for t in ta if t.is_active()]

def find_overdue_tasks(ta):
    '''search with brute force for all overdue tasks'''
    return [t for t in find_active_tasks(ta) if t.is_overdue()]

def find_done_tasks(ta):
    '''search with brute force for all completed tasks'''
    return [t for t in ta if t.completed()]
    

